<template>
  <el-card>
    <!-- 标 题 -->
    <template #header>
        <h2>问卷管理
          <el-button type="primary" @click="addDrawer=true">添加问卷</el-button>
        </h2>
    </template>
    <!-- 问卷管理信息展示 -->

        <el-input placeholder="请输入内容" v-model="searchValue">
          <el-select style="width:110px" v-model="searchField" slot="prepend" placeholder="请选择">
            <el-option label="手机" value="phone"></el-option>
            <el-option label="邮箱" value="email"></el-option>
            <el-option label="问卷名称" value="papername"></el-option>
          </el-select>
          <el-button @click="getPapers(params)" slot="append" icon="el-icon-search"></el-button>
        </el-input>

      <el-table v-loading="loading" :data="papers" border stripe>
        <el-table-column align="center" prop="papername" label="问卷名称" width="200"></el-table-column>
        <el-table-column align="center" prop="classname" label="班级" width="180"></el-table-column>
        <el-table-column align="center" prop="ctime" label="日期" width="100">
          <template #default="{row}">{{moment(row.ctime).locale('zh-cn').fromNow()}}</template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="360">
          <template #default="{row}">
            <el-button type="primary" plain @click="editShow(row)">
              编辑<i class="el-icon-edit"></i></el-button>
            <el-button type="danger" plain @click="del(row._id)">
              删除<i clss="el-icon-delete"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @current-change="change" style="margin:15px 0" :page-size="perPage"
      :total="count" background layout="prev, pager, next"></el-pagination>

      <el-drawer v-loading="addLoading"
      size="400px" title="添加问卷" :visible.sync="addDrawer" direction="rtl">
        <el-form label-width="80px" size="mini" :model="addForm" :rules="addRules" ref="addForm">
          <el-form-item label="问卷名" prop="papername">
            <el-input v-model="addForm.papername"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="classname">
            <el-select v-model="addForm.classname">
              <el-option v-for="item in classes"
              :key="item._id" :label="item.classname" :value="item.classname"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选项" prop="items">
            <el-tree @check-change="addItemChange"
            show-checkbox node-key="_id" :render-after-expand="false"
            :data="items" :props="{label:'itemname'}"></el-tree>
          </el-form-item>

          <el-form-item label="大纲" prop="outlines">
            <el-tree @check-change="addOutlineChange"
            show-checkbox node-key="_id" :render-after-expand="false"
            :data="outlines" :props="{label:'outlinename'}"></el-tree>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="addSave">保存</el-button>
            <el-button @click="addDrawer=false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

      <el-drawer v-loading="editLoading"
      size="400px" title="编辑问卷" :visible.sync="editDrawer" direction="rtl">
        <el-form label-width="80px" size="mini" :model="editForm" :rules="editRules" ref="editForm">
          <el-form-item label="问卷名" prop="papername">
            <el-input v-model="editForm.papername"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="classname">
            <el-select v-model="editForm.classname">
              <el-option v-for="item in classes"
              :key="item._id" :label="item.classname" :value="item.classname"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选项" prop="items">
            <el-tree ref="items" @check-change="editItemChange"
            show-checkbox node-key="_id" :render-after-expand="false"
            :data="items" :props="{label:'itemname'}"></el-tree>
          </el-form-item>

          <el-form-item label="大纲" prop="outlines">
            <el-tree ref="outlines" @check-change="editOutlineChange"
            show-checkbox node-key="_id" :render-after-expand="false"
            :data="outlines" :props="{label:'outlinename'}"></el-tree>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="editSave">保存</el-button>
            <el-button @click="editDrawer=false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

  </el-card>
</template>

<script>
import { createNamespacedHelpers } from 'vuex';
import moment from 'moment';

const { mapActions, mapState } = createNamespacedHelpers('papers');

export default {
  data() {
    // 验证
    const addValidatePapername = async (rule, value, callback) => {
      const { data } = await this.apis.papersExist({
        field: 'papername',
        value,
      });
      if (!data) {
        callback();
      } else {
        callback(new Error('问卷名重复'));
      }
    };
    const editValidatePapername = (rule, value, callback) => {
      if (value === this.row.papername) {
        callback();
      } else {
        addValidatePapername(rule, value, callback);
      }
    };
    return {
      searchField: '',
      searchValue: '',
      page: 1,
      perPage: 3,
      row: {},
      editDrawer: false,
      editLoading: false,
      editForm: {
        papername: '',
        classname: '',
        items: [],
        outlines: [],
      },
      addDrawer: false,
      addLoading: false,
      addForm: {
        items: [],
        outlines: [],
      },
      classes: [],
      items: [],
      outlines: [],
      // 添加问卷验证规则
      addRules: {
        papername: [
          { required: true, message: '请输入问卷名称', trigger: 'blur' },
          { validator: addValidatePapername, trigger: 'blur' },
        ],
        classname: [
          { required: true, message: '请选择班级', trigger: 'blur' },
        ],
        items: [
          { required: true, message: '请选择选项', trigger: 'blur' },
        ],
        outlines: [
          { required: true, message: '请选择大纲', trigger: 'blur' },
        ],
      },
      // 编辑问卷验证规则
      editRules: {
        papername: [
          { required: true, message: '请输入问卷名称', trigger: 'blur' },
          { validator: editValidatePapername, trigger: 'blur' },
        ],
        classname: [
          { required: true, message: '请选择班级', trigger: 'blur' },
        ],
        items: [
          { required: true, message: '请选择选项', trigger: 'blur' },
        ],
        outlines: [
          { required: true, message: '请选择大纲', trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    params() {
      const p = {
        page: this.page,
        perPage: this.perPage,
      };
      if (this.searchField && this.searchValue) {
        p.searchField = this.searchField;
        p.searchValue = this.searchValue;
      }
      return p;
    },
    ...mapState(['count', 'papers', 'loading']),
  },
  async created() {
    this.getPapers(this.params);
    const { data: { result } } = await this.apis.getClasses({ perPage: 999 });
    this.classes = result;
    const { data } = await this.apis.getItems();
    this.items = data;
    this.classes = result;
    const { data: data2 } = await this.apis.getOutlines();
    this.outlines = data2;
  },
  methods: {
    change(e) {
      this.page = e;
      this.getPapers(this.params);
    },
    // 删除问卷
    del(id) {
      this.$confirm('确定删除吗？').then(async () => {
        this.apis.deletePapers(id);
        this.getPapers(this.params);
      }).catch(() => {});
    },
    // 保存编辑问卷
    editSave() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        await this.apis.editPapers(this.editForm.id, {
          papername: this.editForm.papername,
          classname: this.editForm.classname,
          items: this.editForm.items,
          outlines: this.editForm.outlines,
        });
        this.editDrawer = false;
        this.getPapers(this.params);
      });
    },
    // 编辑问卷信息展示
    editShow(row) {
      this.row = row;
      const { _id: id } = row;
      this.editDrawer = true;
      this.editForm.id = id;
      this.editForm.classname = row.classname;
      this.editForm.papername = row.papername;
      setTimeout(() => {
        this.$refs.items.setCheckedNodes(row.items);
        this.$refs.outlines.setCheckedNodes(row.outlines);
      }, 0);
    },
    // 保存添加问卷
    addSave() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        await this.apis.addPapers({
          papername: this.addForm.papername,
          classname: this.addForm.classname,
          outlines: this.addForm.outlines,
          items: this.addForm.items,
        });
        this.addDrawer = false;
        this.getPapers(this.params);
      });
    },
    // 编辑问卷时选项的变化
    editItemChange(data, flag) {
      this.itemChange(data, flag, this.editForm);
    },
    // 编辑问卷时大纲的变化
    editOutlineChange(data, flag) {
      this.outlineChange(data, flag, this.editForm);
    },
    // 添加问卷时选项的变化
    addItemChange(data, flag) {
      this.itemChange(data, flag, this.addForm);
    },
    // 添加问卷时大纲的变化
    addOutlineChange(data, flag) {
      this.outlineChange(data, flag, this.addForm);
    },
    outlineChange(data, flag, obj) {
      if (data.children.length > 0) {
        return;
      }
      if (flag) {
        obj.outlines.push(data);
      } else {
        const pos = obj.outlines.indexOf(data);
        obj.outlines.splice(pos, 1);
      }
    },
    itemChange(data, flag, obj) {
      if (data.children.length > 0) {
        return;
      }
      if (flag) {
        obj.items.push(data);
      } else {
        const pos = obj.items.indexOf(data);
        obj.items.splice(pos, 1);
      }
    },
    moment,
    ...mapActions(['getPapers']),
  },
};
</script>
